package com.tddx.activiti.common.propertyeditor;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;

/**
 * date编辑器，用于controller接收date参数
 * @author zhaoyanwei
 *
 */
public class DateEditorSupport extends PropertyEditorSupport{

	public void setAsText(String value) throws IllegalArgumentException {
		try {
			if(StringUtils.isEmpty(value)){
				setValue(null);
			}else if(value.contains("-")){
				setValue(DateUtils.parseDate(value, "yyyy-MM-dd hh:mm", "yyyy-MM-dd hh:mm:ss", "yyyy-MM-dd"));
			}else{
				setValue(new Date(Long.valueOf(value)));
			}
		} catch (ParseException e) {
			e.printStackTrace();
			setValue(null);
			throw new IllegalArgumentException("date parse Exception");
		}
	}
	
	public String getAsText() {
		return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
				.format((Date) getValue());
	}
}
